import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';

typedef ApiCallback = void Function(bool isSuccess);

class Map_searchLogic extends GetxController {
  LatLng latLng = LatLng(39.909187, 116.397451); //默认北京
  late Poi poi;
  List<Poi> poiList = [];

  late AMapController mapController;
  TextEditingController editingController = TextEditingController();

  void onMapCreated(AMapController controller) {
    mapController = controller;
    getApprovalNumber();
  }

  /// 获取审图号
  void getApprovalNumber() async {
    //普通地图审图号
    String? mapContentApprovalNumber =
        await mapController.getMapContentApprovalNumber();
  }

  Future<List<Poi>> doSearch(String keyword) async {
    AmapSearch amapSearch = AmapSearch.instance;
    // 初始化高德地图SDK
    await amapSearch.init('845bdcecb1f3e2127922387153804eae');

    /// !重要: 通过AmapSearchDisposeMixin释放native端的对象, 否则native端会内存泄漏!
    // 执行搜索
    final List<Poi> poiList = await amapSearch.searchKeyword(keyword);
    this.poiList = poiList;
    print("${keyword} 的搜索结果有 ${poiList.length} 条:");
    for (Poi poi in poiList) {
      print('${poi}');
    }
    return poiList;
  }

  void poiItemClicked(Poi item) {
    poi = item;
    latLng = LatLng(item.latLng!.latitude, item.latLng!.longitude);
  }

  void saveNewPoi({ApiCallback? callback}) {
    if (poi != null) {
      Map<String, Object> map = {
        "latitude": poi.latLng!.latitude,
        "longitude": poi.latLng!.longitude,
        "province": poi.provinceName.toString(),
        "city": poi.cityName.toString(),
        "district": poi.adName.toString(),
        "adCode": poi.adCode.toString(),
        "cityCode": poi.cityCode.toString(),
        "address": poi.address.toString(),
        "title": poi.title.toString(),
      };
      WhlApi.saveUserLocation.post(map, hideMsg: true).then((value) {
        if (value.isSuccess()) {
          MyToast.show("漫游成功");
          if (callback != null) {
            callback(true);
          }
        } else {
          MyToast.show("漫游失败");
          if (callback != null) {
            callback(false);
          }
        }
      });
    }
  }
}
